package 力扣日常刷题.木23一月.第11天311;

import 力扣日常刷题.TreeNode;

import java.util.*;

/**
 * @author 帅小伙
 * @date 2022/3/11
 * @description
 */
public class Demo40从上到下打印二叉树 {


    public int[] levelOrder(TreeNode root) {
        if(root == null) {
            return new int[0];
        }

        List<Integer> ans = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);

        while(deque.isEmpty()) {
            for (int i = deque.size(); i > 0; i--) {
                TreeNode pop = deque.pop();
                ans.add(pop.val);
                if(pop.left!= null) deque.add(pop.left);
                if(pop.right!= null) deque.add(pop.right);
            }
        }
        int[] res = new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) res[i] = ans.get(i);
        return res;
    }

}
